package com.hisan.freeride.home.activity;

import android.Manifest;
import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hisan.freeride.R;
import com.hisan.freeride.common.Dialog.ReservationDialogLogok;
import com.hisan.freeride.common.alertwindow.BasePopupWindow;
import com.hisan.freeride.common.alertwindow.ScalePopup;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.event.DataSynEvent;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.ListUtils;
import com.hisan.freeride.common.utils.utils.MyHandlerUtil;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.common.view.AlertDialog;
import com.hisan.freeride.common.view.AlertDialog2;
import com.hisan.freeride.common.view.ListPopup;
import com.hisan.freeride.databinding.ReservationBinding;
import com.hisan.freeride.home.model.Reservation;
import com.hisan.freeride.home.model.RideUser;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tsy.sdk.pay.model.WXBean;
import com.tsy.sdk.pay.weixin.WXPay;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 创建时间 : 2017/6/14
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：预约乘车页面
 */
public class ReservationActivity extends BaseActivity<ReservationBinding> {
    private Reservation myreservation;
    //拨打电话权限返回码
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    //行程id
    private int trip_id;
    //人数选择弹窗
    private ListPopup mListPopup;
    private ListPopup.Builder builder;
    //乘坐人弹窗
    private RadioPopup radioPopup;
    private RadioPopup.Builder rbuilder;
    //标签弹窗
    private ScalePopup scalePopup;
    private List<Integer> integers=new ArrayList<>();
    private int id;
    private int myposition;
    //乘坐人id数组
    public static List<String>ids=new ArrayList<>();
    private String passengers="";
    public AlertDialog mDialog;
    private AlertDialog.Builder mbuilder;
    public AlertDialog2 mDialog2;
    private AlertDialog2.Builder mbuilder2;
    private Intent intent;
    //支付订单账号
    private String pay_no="";
    //订单id数组
    private String pay_ids="";


    @Override
    protected int getLayoutId() {
        return  R.layout.reservation;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        builder=new ListPopup.Builder(this);
        mListPopup=builder.build();
        rbuilder=new RadioPopup.Builder(this);
        radioPopup=rbuilder.build();
        if (!CollectionUtils.isNullOrEmpty(integers))integers.clear();
        Bundle bundle=getIntent().getExtras();
        if (!CollectionUtils.isNullOrEmpty(bundle)){
            id=bundle.getInt("id");
        }
    }

    @Override
    protected void initEvent() {
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.triporder.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(myreservation)){
                if(myreservation.getSurplus()>0)
                    showPopListView(myreservation.getTags());
                else showToast("当前行程预约人数已满,请选择其他行程预约！！");
            }
        });
        mBinding.tel.setOnClickListener(v -> {
            getmDialog("是否打开手机拨号?","取消","确定").show();
        });

    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.get(AppConfig.Tripdetail)
                .tag(this)
                .params("id",id)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            String data=GsonUtils.GsonString(response.body());
                            Reservation reservation=GsonUtils.GsonToBean(data,Reservation.class);
                            myreservation=reservation;
                            if (myreservation.getSurplus()>0){
                                for (int i=1;i<=myreservation.getSurplus();i++){
                                    builder.addItem(i+"人");
                                    integers.add(i);
                                    mListPopup=builder.build();
                                }
                            }
                            mBinding.name.setText(myreservation.getDriver_name());
                            mBinding.logo.setImageURI(myreservation.getDriver_avatar());
                            mBinding.number.setText(myreservation.getHelp_count()+"");
                            mBinding.time.setText(myreservation.getDeparture_time());
                            mBinding.total.setText("剩余" + myreservation.getSurplus() + "人"+","+"可乘"+myreservation.getPeople()+"人");
                            mBinding.site.setText("出发地: "+myreservation.getInitially());
                            mBinding.way.setText("途径地: "+myreservation.getWay());
                            mBinding.plate.setText(myreservation.getCar_no()+"");
                            mBinding.address.setText("目的地: "+myreservation.getDestination());
                            if (!CollectionUtils.isNullOrEmpty(myreservation.getTags())){
                                myreservation.getTags().add(0,new Reservation.TagsBean(0,"免费免责"));
                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                for (int i = 0; i < myreservation.getTags().size(); i++) {
                                    TextView textView = new TextView(ReservationActivity.this);
                                    //设置padding值
                                    textView.setPadding(14, 6, 14, 6);
                                    //设置Margins值
                                    layoutParams.setMargins(10,0,0,0);
                                    textView.setTextSize(11);
                                    if (i==0){
                                        textView.setTextColor(getResources().getColor(R.color.white));
                                        textView.setBackgroundResource(R.drawable.textview_style2); //设置背景
                                    }else {
                                        textView.setTextColor(getResources().getColor(R.color.darkgray));
                                        textView.setBackgroundResource(R.drawable.textview_style); //设置背景
                                    }
                                    textView.setText( myreservation.getTags().get(i).getName());
                                    textView.setLayoutParams(layoutParams);
                                    mBinding.label.addView(textView);
                                }
                            }
                        }
                    }
                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    @Override
    public void onOk() {
        String token=  TokenUtils.getToken();
        if (!CollectionUtils.isNullOrEmpty(token)){
            getRealname();
        }
    }

    //获取乘坐人
    public void getRideUser() {
        OkGo.<List<RideUser>>get(AppConfig.plist)
                .tag(this)
                .execute(new DialogCallback<List<RideUser>>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<RideUser>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())) {
                            if (radioPopup.isShowing())radioPopup.dismiss();
                                rbuilder=new RadioPopup.Builder(ReservationActivity.this);
                                rbuilder.addItem(response.body());
                                radioPopup=rbuilder.build();
                                if (response.body().size() ==5) {
                                    radioPopup.getTypename().setVisibility(View.VISIBLE);
                                    radioPopup.getAddname().setVisibility(View.GONE);
                                } else {
                                    radioPopup.getTypename().setVisibility(View.GONE);
                                    radioPopup.getAddname().setVisibility(View.VISIBLE);
                                }
                        }else {
                            rbuilder.addItem(new ArrayList<>(0));
                            radioPopup=rbuilder.build();
                            radioPopup.getTypename().setVisibility(View.GONE);
                            radioPopup.getAddname().setVisibility(View.VISIBLE);
                        }

                        radioPopup.showPopupWindow();
                        radioPopup.getHome_titel().setText("被保险人乘坐列表");
                        radioPopup.setOnDismissListener(() -> ids.clear());
                        radioPopup.setmOnListPopupItemClickListener((type, radioModel) -> {
                            //添加
                            if (type==1){
                                ids.add(radioModel.getId()+"");
                                //删除
                            }else if (type==2){
                                if (ids.size()>0){
                                    ListUtils.deleteid(ids,radioModel.getId());
                                }
                            }else if (type==3){
                                Bundle bundle=new Bundle();
                                bundle.putInt("id",radioModel.getId());
                                startActivityForResult(RideUserListActivity.class,99,bundle,true);
                            }
                        });

                        radioPopup.setMbuttonlistener(type -> {
                            if (type==1){
                                trip_id=myreservation.getId();
                                if (!CollectionUtils.isNullOrEmpty(ids))passengers= ListUtils.formatStr(ids);
                                if (myreservation.getSurplus()>0){
                                    if (!CollectionUtils.isNullOrEmpty(integers))
                                        triporder(trip_id,integers.get(myposition),passengers,true);
                                }else{
                                    showToast("剩余座位不足");
                                }
                                if (!CollectionUtils.isNullOrEmpty(radioPopup))
                                    radioPopup.dismiss();
                            }else{
                                startActivityForResult(RideUserListActivity.class,99,null,true);
                            }
                        });
                    }
                });
    }


    //获取实名认证
    public void getRealname() {
        int is_realname=  BaseAppLication.getInstance().getIs_realname();
        if (is_realname==1){
            // 检查是否获得了权限（Android6.0运行时权限）
            if (ContextCompat.checkSelfPermission(ReservationActivity.this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
                // 没有获得授权，申请授权
                if (ActivityCompat.shouldShowRequestPermissionRationale(ReservationActivity.this,
                        Manifest.permission.CALL_PHONE)) {
                    // 弹窗需要解释为何需要该权限，再次请求授权
                    showToast("请在应用中开启电话权限");
                    // 帮跳转到该应用的设置界面，让用户手动授权
                    Intent intent1 = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent1.setData(uri);
                    startActivity(intent1);
                }else{
                    // 不需要解释为何需要该权限，直接请求授权
                    ActivityCompat.requestPermissions(ReservationActivity.this,
                            new String[]{Manifest.permission.CALL_PHONE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);
                }
            }else {
                // 已经获得授权，可以打电话
                if (!CollectionUtils.isNullOrEmpty(myreservation)){
                    CallPhone(myreservation.getMobile());
                }
            }
        }else {
            shoewErrorToast("实名认证正在审核中");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(DataSynEvent event) {
        //预约成功弹窗
        if (event.getid()==1){
            finishActivity(true);
            //关闭标签弹窗
        }else if (event.getid()==2){
            if (!CollectionUtils.isNullOrEmpty(scalePopup))
                scalePopup.dismiss();
            //确认预约
        }else if (event.getid()==3){
            if (!CollectionUtils.isNullOrEmpty(scalePopup))
                scalePopup.dismiss();
            mListPopup.showPopupWindow();
            mListPopup.setOnListPopupItemClickListener(position -> {
                if (!CollectionUtils.isNullOrEmpty(myreservation)) {
                    if (!CollectionUtils.isNullOrEmpty(mListPopup)) mListPopup.dismiss();
                    myposition = position;
                    mbuilder2 = new AlertDialog2.Builder(this);
                    mbuilder2.setMessage("为了您的旅程得到相应的安全保障，在预约乘车时将要求您购买相应的保险服务，感谢您使用顺风车平台！")
                            .setTopImage(R.mipmap.certification_prompt)
                            .setNegativeButton("不购买", (dialog, which) ->  {
                                if (mDialog2.isShowing())mDialog2.dismiss();
                                trip_id=myreservation.getId();
                                if (myreservation.getSurplus()>0){
                                    if (!CollectionUtils.isNullOrEmpty(integers))
                                        triporder(trip_id,integers.get(myposition),passengers,false);
                                }else{
                                    showToast("剩余座位不足");
                                }
                            })
                            .setPositiveButton("购买", (dialog, which) -> {
                                if (mDialog2.isShowing())mDialog2.dismiss();
                                getRideUser();
                            });
                    mDialog2 = mbuilder2.create();
                    mDialog2.show();
                }
            });
        }else if (event.getid()==4){
            RotationActivity.skip(ReservationActivity.this, AppConfig.agreement);
        }
    }

    //预约行程
    private void triporder(int trip_id, int people,String passengers,boolean ispay) {
        HttpParams params=new HttpParams();
        params.put("id",trip_id);
        params.put("people",people);
        params.put("passengers",passengers);
        OkGo.post(AppConfig.Triporder)
                .tag(this)
                .params(params)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                if (ispay){
                                    String data=  GsonUtils.GsonString(response.body());
                                    try {
                                        JSONObject jsonObject=new JSONObject(data);
                                        pay_ids=jsonObject.getString("ids");
                                        if (!CollectionUtils.isNullOrEmpty(pay_ids))
                                            WxPayopen(pay_ids);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }else {
                                    if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                                    setResult(99,intent);
                                    ReservationDialogLogok.getInstance().show(getSupportFragmentManager(), "DialogLogok");
                                }
                            }


                        }else {
                            showError(response);
                        }
                    }
                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    //付款
    private void WxPayopen(String  ids) {
        OkGo.post(AppConfig.unifiedorder)
                .tag(this)
                .params("ids",ids)
                .params("module",1)
                .params("mode",1)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(Response<Object> response) {
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                try {
                                    String data= GsonUtils.GsonString(response.body());
                                    JSONObject json=new JSONObject(data);
                                    pay_no= json.getString("pay_no");
                                    JSONObject mjson=json.getJSONObject("pay_data");
                                    if (!CollectionUtils.isNullOrEmpty(mjson)){
                                        WXBean wxBean=new WXBean();
                                        String appid=mjson.getString("appid");
                                        wxBean.setAppid(appid);
                                        int partnerid=mjson.getInt("partnerid");
                                        wxBean.setPartnerid(partnerid);
                                        String prepayid=mjson.getString("prepayid");
                                        wxBean.setPrepayid(prepayid);
                                        String pack=mjson.getString("package");
                                        wxBean.setPackageX(pack);
                                        String Sign=mjson.getString("sign");
                                        wxBean.setSign(Sign);
                                        String noncestr=mjson.getString("noncestr");
                                        wxBean.setNoncestr(noncestr);
                                        int timestamp=mjson.getInt("timestamp");
                                        wxBean.setTimestamp(timestamp);
                                        if (!CollectionUtils.isNullOrEmpty(wxBean))
                                            doWXPay(pay_no,wxBean);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else {
                                showError(response);
                            }
                        }
                    }
                    @Override
                    public void onError(Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ids.clear();
        EventBus.getDefault().unregister(this);
    }

    private void CallPhone(String number) {
        if (CollectionUtils.isNullOrEmpty(number)) {
            showToast("号码不能为空！");
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    if (!CollectionUtils.isNullOrEmpty(myreservation))
                        CallPhone(myreservation.getMobile());
                } else {
                    showToast("电话授权失败！");
                }
                break;
            }
        }
    }

    //显示标签
    private void showPopListView( List<Reservation.TagsBean> datas) {
        if (!CollectionUtils.isNullOrEmpty(datas)) {
            scalePopup = new ScalePopup(this, datas);
            if (!CollectionUtils.isNullOrEmpty(scalePopup)) scalePopup.showPopupWindow();
        }
    }


    /**
     * 微信支付
     * @param pay_param 支付服务生成的支付参数
     */
    private void doWXPay(String pay_no,WXBean pay_param) {
        String wx_appid = AppConfig.APP_ID;     //替换为自己的appid
        WXPay.init(getApplicationContext(), wx_appid);      //要在支付前调用
        WXPay.getInstance().doPay(pay_param, new WXPay.WXPayResultCallBack() {
            //支付成功
            @Override
            public void onSuccess() {
                showSuccessToast("付款成功，如果您的行程被系统或车主取消，我们将通过微信红包的方式，给您返还保险费用。");
                if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                setResult(99,intent);
                ReservationDialogLogok.getInstance().show(getSupportFragmentManager(), "DialogLogok");

            }
            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:{
                        shoewErrorToast("未安装微信或微信版本过低");
                        break;
                    }
                    case WXPay.ERROR_PAY_PARAM:{
                        shoewErrorToast("参数错误");
                        break;
                    }
                    //支付失败
                    case WXPay.ERROR_PAY:{
                        mbuilder = new AlertDialog.Builder(ReservationActivity.this);
                        mbuilder.setMessage("付款失败，您可以通过【用户中心-我的保险】进行再次支付，如果您未支付保险费用，车主将有权拒绝与您同行")
                                .setTopImage(R.mipmap.certification_prompt)
                                .setNegativeButton("取消", (dialog, which) ->  {
                                    if (mDialog.isShowing())mDialog.dismiss();
                                })
                                .setPositiveButton("确定", (dialog, which) -> {
                                    Bundle bundle=new Bundle();
                                    bundle.putInt("type",1);
                                    startActivityForResult(InsuranceActivity.class,99,bundle,true);
                                    finishActivity(true);
                                });
                        mDialog = mbuilder.create();
                        mDialog.show();
                        break;
                    }
                }
            }
            @Override
            public void onCancel() {
                if (mDialog.isShowing())mDialog.dismiss();
                checkpay(pay_no);
            }
        });
        if (radioPopup.isShowing())radioPopup.dismiss();
        new MyHandlerUtil().getHandler2().postDelayed(() -> checkpay(pay_no),1000);
    }

    //判断支付是否成功
    private void checkpay(String pay_no){
        OkGo.post(AppConfig.checkpay)
                .tag(this)
                .params("pay_no",pay_no)
                .execute(new DialogCallback<Object>(this){
                    @Override
                    public void onSuccess(Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                String data=GsonUtils.GsonString(response.body());
                                try {
                                    JSONObject jsonObject=new JSONObject(data);
                                    boolean status= jsonObject.getBoolean("status");
                                    if (status==false){
                                        mbuilder = new AlertDialog.Builder(ReservationActivity.this);
                                        mbuilder.setMessage("当前订单支付状态")
                                                .setTopImage(R.mipmap.certification_prompt)
                                                .setNegativeButton("未完成", (dialog, which) ->  {
                                                    if (mDialog.isShowing())mDialog.dismiss();
                                                    pay();
                                                })
                                                .setPositiveButton("已完成", (dialog, which) -> {
                                                    if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                                                    setResult(99,intent);
                                                    ReservationDialogLogok.getInstance().show(getSupportFragmentManager(), "DialogLogok");
                                                });
                                        mDialog = mbuilder.create();
                                        mDialog.show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }else {
                                showError(response);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==99){
            getRideUser();
        }
    }
    //继续支付弹窗
    private void pay(){
        mbuilder = new AlertDialog.Builder(ReservationActivity.this);
        mbuilder.setMessage("是否继续支付当前行程订单？")
                .setTopImage(R.mipmap.certification_prompt)
                .setNegativeButton("取消支付", (dialog, which) ->  {
                    if (mDialog.isShowing())mDialog.dismiss();
                })
                .setPositiveButton("继续支付", (dialog, which) -> {
                    if (mDialog.isShowing())mDialog.dismiss();
                    if (!CollectionUtils.isNullOrEmpty(pay_ids)){
                        WxPayopen(pay_ids);
                    }
                });
        mDialog = mbuilder.create();
        mDialog.show();
    }

    static class RadioPopup extends BasePopupWindow {
        private ListView mListView;
        private OnListPopupItemClickListener mOnListPopupItemClickListener;
        private ButtonClickListener mbuttonlistener;
        public TextView home_titel;
        public TextView cancel;
        public TextView ok;
        public TextView typename;
        public LinearLayout adduser;
        public LinearLayout addname;

        public TextView getHome_titel() {
            return home_titel;
        }
        public LinearLayout getAddname() {
            return addname;
        }
        public TextView getTypename() {
            return typename;
        }


        private RadioPopup(Activity context) {
            super(context);
        }
        private RadioPopup(Activity context, Builder builder){
            this(context);
            mListView= (ListView) mPopupView.findViewById(R.id.popup_list);
            home_titel=mPopupView.findViewById(R.id.nane);
            cancel=mPopupView.findViewById(R.id.cancel);
            adduser=mPopupView.findViewById(R.id.adduser);
            adduser.setVisibility(View.VISIBLE);
            addname=mPopupView.findViewById(R.id.addname);
            typename=mPopupView.findViewById(R.id.typename);
            cancel.setOnClickListener(v -> {
                if (isShowing()) dismiss();
            });
            ok=mPopupView.findViewById(R.id.ok);
            ok.setOnClickListener(v -> {
                if (mbuttonlistener!=null){
                    //确认
                    mbuttonlistener.onButton(1);
                    if (isShowing()) dismiss();
                }
            });
            addname.setOnClickListener(v -> {
                if (mbuttonlistener!=null){
                    //添加乘坐人
                    mbuttonlistener.onButton(0);
                }
            });
            setAdapter(context,builder);
        }

        public static class Builder{
            private List<RideUser> mItemEventList;
            private Activity mContext;
            public Builder(Activity context) {
                mContext = context;
            }
            public RadioPopup.Builder addItem(List<RideUser> items){
                mItemEventList=new ArrayList<>();
                mItemEventList=items;
                return this;
            }
            public List<RideUser> getItemEventList() {
                return mItemEventList;
            }
            public RadioPopup build(){
                return new RadioPopup(mContext,this);
            }

        }
        public class MyAdapter extends BaseAdapter {
            private List<RideUser> data;
            private Context context;
            public MyAdapter(List<RideUser> data, Context context) {
                this.data = data;
                this.context = context;
            }
            @Override
            public int getCount() {
                return data.size()==0? 0:data.size();
            }
            @Override
            public Object getItem(int i) {
                return data.get(i);
            }
            @Override
            public long getItemId(int i) {
                return i;
            }
            @Override
            public View getView(final int i, View view, ViewGroup viewGroup) {
                MyAdapter.ViewHoder hd;
                if (view == null) {
                    hd = new MyAdapter.ViewHoder();
                    LayoutInflater layoutInflater = LayoutInflater.from(context);
                    view = layoutInflater.inflate(R.layout.radio_item, null);
                    hd.name = (TextView) view.findViewById(R.id.name);
                    hd.id = (TextView) view.findViewById(R.id.id);
                    hd.type = (TextView) view.findViewById(R.id.type);
                    hd.edit = (LinearLayout) view.findViewById(R.id.edit);
                    hd.check = (CheckBox) view.findViewById(R.id.check);
                    view.setTag(hd);
                }
                RideUser mModel = data.get(i);
                hd = (MyAdapter.ViewHoder) view.getTag();
                hd.name.setText(mModel.getName());
                hd.id.setText(mModel.getId()+"");
                hd.type.setText(mModel.getCard_type()+" "+mModel.getCard_number());
                final MyAdapter.ViewHoder hdFinal = hd;
                if (i==0) {
                    mModel.setIscheck(true);
                    ids.clear();
                    ids.add(mModel.getId()+"");
                    view.setOnClickListener(null);
                }else {
                    if (i>0) {
                        view.setOnClickListener(view1 -> {
                            CheckBox checkBox = hdFinal.check;
                            if (checkBox.isChecked()) {
                                data.get(i).setIscheck(false);
                                checkBox.setChecked(false);
                                if (mOnListPopupItemClickListener!=null){
                                    RideUser radioModel=data.get(i);
                                    mOnListPopupItemClickListener.onItemClick(2,radioModel);
                                }
                            } else {
                                checkBox.setChecked(true);
                                data.get(i).setIscheck(true);
                                if (mOnListPopupItemClickListener!=null){
                                    RideUser radioModel=data.get(i);
                                    mOnListPopupItemClickListener.onItemClick(1,radioModel);
                                }
                            }
                        });
                    }
                }
                hd.check.setChecked(mModel.isIscheck());
                hd.edit.setOnClickListener(v -> {
                    if (mOnListPopupItemClickListener!=null){
                        RideUser radioModel=data.get(i);
                        mOnListPopupItemClickListener.onItemClick(3,radioModel);
                    }
                });

                return view;
            }

            class ViewHoder {
                TextView name,type,id;
                LinearLayout edit;
                CheckBox check;
            }

        }

        private void setAdapter(Activity context, Builder builder) {
            if (builder.getItemEventList()==null||builder.getItemEventList().size()==0)return;
            final  MyAdapter adapter=new MyAdapter(builder.getItemEventList(),context);
            adapter.notifyDataSetChanged();
            mListView.setAdapter(adapter);
        }

        @Override
        protected View getClickToDismissView() {
            return mPopupView;
        }

        @Override
        public View getPopupView() {
            return getPopupViewById(R.layout.popup_list);
        }

        @Override
        public View getAnimaView() {
            return mPopupView.findViewById(R.id.popup_anima);
        }

        @Override
        public Animator getExitAnimator() {
            return null;
        }

        public void setmOnListPopupItemClickListener(OnListPopupItemClickListener mOnListPopupItemClickListener) {
            this.mOnListPopupItemClickListener = mOnListPopupItemClickListener;
        }

        public void setMbuttonlistener(ButtonClickListener mbuttonlistener) {
            this.mbuttonlistener = mbuttonlistener;
        }

    }

    private interface OnListPopupItemClickListener{
        void onItemClick(int type,RideUser radioModel);
    }
    public interface ButtonClickListener{
        void onButton(int type);
    }


}
